<template>
  <div class="app-container">
    <!--    <button @click="handlePay">测试</button>-->
    <el-form :model="queryParams" ref="queryParamsRef" :inline="true">
      <el-form-item label="昵称" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="登录账号名" prop="userCode">
        <el-input v-model="queryParams.userCode" placeholder="请输入账号" />
      </el-form-item>
      <el-form-item label="商户号" prop="merchantNo">
        <el-input v-model="queryParams.merchantNo" placeholder="请输入商户号" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row>
      <el-button icon="Plus" type="warning" @click="handleAdd">新增商户账号</el-button>
    </el-row>
    <el-table :data="tableData">
      <el-table-column align="center" label="昵称" prop="userName" />
      <el-table-column align="center" label="账号名" prop="userCode" />
      <el-table-column align="center" label="商户号" prop="merchantNo" />
      <el-table-column align="center" label="状态" prop="hasUse">
        <template #default="scope">
          <el-switch v-model="scope.row.hasUse" :active-value="1" :inactive-value="0"
            @change="changeState(scope.row.merchantNo)" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="通道" prop="channelName" />
      <el-table-column align="center" label="开通API" prop="openApi">
        <template #default="scope">
          <el-button size="small" plain type="success" @click="downloadHandle(scope.row)"
            v-show="scope.row.openApi">下载Key
          </el-button>
          <!-- <div v-show="scope.row.openApi">已开通</div> -->
          <el-button size="small" type="success" @click="handleOpen(scope.row)" v-show="!scope.row.openApi">开通
          </el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" label="重置密码">
        <template #default="scope">
          <el-button size="small" type="primary" plain @click="resetPwd(scope.row)">重置</el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" label="telegram群服务是否配置" prop="botConfig">
        <template #default="scope">
          <div v-show="scope.row.botConfig">是</div>
          <el-button v-show="!scope.row.botConfig" plain size="small" type="success" @click="setBotHandle(scope.row)">配置
          </el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="300px">
        <template #default="scope">
          <el-button size="small" type="warning" plain @click="changeBalance(scope.row)">修改金额</el-button>
          <el-button size="small" @click="infoHandler(scope.row)">详情</el-button>
          <el-button size="small" type="warning" @click="modifyHandler(scope.row)">修改</el-button>
          <el-button size="small" type="info" @click="handleDetail(scope.row)">流水详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />
    <el-dialog v-model="show" :title="title" @close="resetHandle" width="40%">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="用户昵称" prop="userName">
          <el-input v-model="form.userName" :disabled="!!form.merchantId" placeholder="请输入用户昵称" />
        </el-form-item>
        <el-form-item label="登录账号" prop="userCode">
          <el-input v-model="form.userCode" :disabled="!!form.merchantId" placeholder="请输入登录账号" />
        </el-form-item>
        <el-form-item label="父级商户ID" prop="parentId">
          <el-input v-model="form.parentId" :disabled="!!form.merchantId" placeholder="请输入父级商户id" />
        </el-form-item>
        <el-form-item label="代付费率(%)" prop="outerRate">
          <el-input v-model="form.outerRate" placeholder="请输入代付费率(%)"></el-input>
        </el-form-item>
        <el-form-item label="代收费率(%)" prop="innerRate">
          <el-input v-model="form.innerRate" placeholder="请输入代收费率(%)"></el-input>
        </el-form-item>
        <el-form-item label="单笔代收费" prop="outerPrice">
          <el-input v-model="form.outerPrice" placeholder="请输入单笔代收费"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetHandle">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">提 交</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="detailShow" title="资金变动详情" destroy-on-close>
      <change-detail :merchantNo="merchantNo"></change-detail>
    </el-dialog>
    <el-dialog v-model="infoShow" title="商户详情" destroy-on-close>
      <info-detail :infoData="infoData"></info-detail>
    </el-dialog>
    <el-dialog v-model="changeShow" title="修改金额" destroy-on-close width="500" @close="resetHandle">
      <el-form :model="changeForm" ref="changeFormRef" :rules="rules">
        <el-form-item label="金额" prop="amount">
          <el-input v-model="changeForm.amount" placeholder="请输入账号" style="width: 240px" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetHandle">取消</el-button>
          <el-button type="primary" @click="requestHandle"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  changeRate,
  changeUse,
  merchantAdd,
  merchantPage,
  openApi,
  resetPassword,
  setBotConfig,
  changeAmount,
  loadKey,
  downloadKey
} from "@/api/userManagement";
import { ElMessage, ElMessageBox } from "element-plus";
import ChangeDetail from "./components/detail.vue"
import InfoDetail from "./components/info.vue"
import { download2 } from "@/utils/request.js";

const { proxy } = getCurrentInstance();
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: "",
    userCode: "",
    merchantNo: "",
  },
  form: {},
  changeForm:{},
  rules: {
    userName: [
      { required: true, message: "用户昵称不能为空", trigger: "blur" },
    ],
    userCode: [
      { required: true, message: "登录账号不能为空", trigger: "blur" },
    ],
    outerRate: [
      { required: true, message: "代付费率不能为空", trigger: "blur" },
    ],
    innerRate: [
      { required: true, message: "代收费率不能为空", trigger: "blur" },
    ],
    outerPrice: [
      { required: true, message: "单笔代收费不能为空", trigger: "blur" },
    ],
    amount: [
      { required: true, message: "金额必填", trigger: "blur" },
    ],
  },
});
const { queryParams, form, rules, changeForm } = toRefs(data);
const total = ref(0);
const show = ref(false);
const changeShow=ref(false)
const title = ref('新增商户')
const merchantNo = ref("");
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
const tableData = ref([]);
/** 查询参数列表 */
function getList() {
  merchantPage(queryParams.value).then((res) => {
    const { total: totalNum, data } = res.data;
    tableData.value = data;
    total.value = totalNum;
  });
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryParamsRef");
  handleQuery();
}
function handleAdd() {
  show.value = true;
  title.value = '新增商户'
}
// 提交
function handleSubmit() {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      if (form.value.merchantId) {
        changeRate(form.value).then((res) => {
          ElMessage.success("修改商户费率成功!");
          getList();
        });
      } else {
        merchantAdd(form.value).then((res) => {
          ElMessageBox.alert(
            ` 初始密码为  ${res.data}`,
            '新增商户成功!',
            {
              type: 'success',
              center: true,
            }
          )
          getList();
        });
      }

      form.value = {};
      show.value = false;
    }
  });
}
// 重置商户密码
function resetPwd(row) {
  ElMessageBox.confirm('是否重置密码？', '重置密码', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    resetPassword({ merchantNo: row.merchantNo }).then((res) => {
      // ElMessage.success(`重置商户密码成功! 初始密码为  ${res.data}`)
      ElMessageBox.alert(
        ` 初始密码为  ${res.data}`,
        '重置商户密码成功!',
        {
          type: 'success',
          center: true,
        }
      )
    })
  })
    .catch(() => {
      ElMessage.warning('取消重置密码！')
    })

}
// 修改
function modifyHandler(row) {
  const rowData = row;
  show.value = true;
  title.value = '商户信息'
  form.value = rowData;
}
// 取消
function resetHandle() {
  proxy.resetForm("formRef");
  proxy.resetForm("changeFormRef");
  changeShow.value = false;
  changeForm.value = {};

  show.value = false;
  form.value = {};
}
const detailShow = ref(false);
function handleDetail(row) {
  merchantNo.value = row.merchantNo;
  detailShow.value = true;
}
const infoData = ref({});
const infoShow = ref(false);
function infoHandler(row) {
  infoShow.value = true;
  infoData.value = row;
}
// 修改状态
function changeState(id) {
  changeUse({ merchantNo: id }).then((res) => {
    ElMessage.success("修改状态成功！");
    getList();

  });
}
// 开通Api
function handleOpen(row) {

  ElMessageBox.prompt('请输入商户公钥', '开通API', {
    inputType: 'textarea',
    inputPlaceholder: '请输入商户公钥',
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  }).then(({ value }) => {
    if (!value) {
      ElMessage.warning('请输入商户公钥！')
    } else {
      const data = {
        merchantNo: row.merchantNo,
        merchantKey: value,
      };
      openApi(data).then((res) => {
        ElMessage.success('开通Api成功')
        getList();
      });
    }
  })
    .catch(() => {
      ElMessage.warning('取消开通API！')
    })

}
// 下载加密Key
function downloadHandle(row) {
  loadKey({merchantNo:row.merchantNo}).then((res) => {
    const blob = new Blob([res.data], { type: 'application/octet-stream' });
    const downloadElement = document.createElement('a');
    downloadElement.href = window.URL.createObjectURL(blob);
    downloadElement.download = `${row.userName}.key`;
    document.body.appendChild(downloadElement);
    downloadElement.click();
    document.body.removeChild(downloadElement);
  })

}
// 配置机器人
function setBotHandle(row) {
  ElMessageBox.prompt('请输入telegram群id', '配置机器人', {
    inputType: 'textarea',
    inputPlaceholder: '请输入telegram群id',
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  }).then(({ value }) => {
    if (!value) {
      ElMessage.warning('请输入telegram群id！')
    } else {
      const data = {
        merchantNo: row.merchantNo,
        chatId: value,
      };
      setBotConfig(data).then((res) => {
        ElMessage.success('配置机器人成功！')
        getList();
      });
    }
  })
    .catch(() => {
      ElMessage.warning('取消配置机器人！')
    })

}
const amountId=ref('')
// 修改金额
function changeBalance(row) {
  changeShow.value = true;
  amountId.value = row.merchantNo;
}
function requestHandle(){
  proxy.$refs["changeFormRef"].validate((valid) => {
    if (valid) {
      const data={
        changeBalance: changeForm.value.amount,

        merchantNo: amountId.value
      }
      changeAmount(data).then((res) => {
        ElMessage.success('修改金额成功！')
        resetHandle();
        getList();
      });
    }})
}
function handlePay() {
  window.open("upi://pay?ver=01&mode=02&orgId=00009&tid=&tr=2563934A&tn=&pa=wlpos.2563934a@kvb&pn=BALAJI TRANSPORT COMPANY&mc=4789&am=&mid=0091410A0012019&mtid=2563934A&qrMedium=04")
}

getList();
</script>

<style scoped>
.useStatus {
  color: #409eff;
}

.red {
  color: red;
}
</style>
